package com.fly.snailrun.domain.dto;

import lombok.Data;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.FrameGrabber;

@Data
public class VideoInfo {

    private FFmpegFrameGrabber grabber;

    private String path;

    private String name;

    private long duration;

    private long frames;

    private double frameRate;

    private Integer width;

    private Integer height;

    private void init() throws FrameGrabber.Exception {
        grabber.start();
        this.frames = grabber.getLengthInFrames();
        this.frameRate = grabber.getFrameRate();
        this.height = grabber.getImageHeight();
        this.width = grabber.getImageWidth();
        this.duration = computeDuration();
    }

    public VideoInfo(String path) {
        try {
            this.grabber = FFmpegFrameGrabber.createDefault(path);
            init();
        } catch (FrameGrabber.Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 计算时长
     * 不保留小数，向上取整
     * duration = 1 * 1000* 1000 * frames  /frameRate
     *
     * @return
     */
    private long computeDuration() {
        return Math.round(1000 * 1000 * frames / frameRate);
    }

    public long computeDuration(Double speed) {
        return Math.round(1000 * 1000 * frames / (frameRate * speed));
    }
}
